import { uiEditorModel } from '@renderer/UIEditor/model/ui-editor-model'
import s from '../UITools.module.less'
import { NumberInput } from '../NumberInput'
import { StringInput } from '../StringInput'
import { Divider } from '../Divider'
import { ToolButton } from '../ToolButton'
import Color from 'color'

function fixColorString(color: string) {
  try {
    return Color(color).hex().toString().toLocaleLowerCase()
  } catch (err) {
    return color
  }
}

export function TextTools(props: { textId: string }) {
  const { useOneText } = uiEditorModel.useState
  const text = useOneText(props.textId)

  if (!text) {
    return (
      <div className={s.uiToolsInfoLine}>
        <span>text {props.textId} not found!</span>
      </div>
    )
  }

  return (
    <>
      <div className={s.uiToolsInfoLine}>
        <span className={s.uiToolsInfoLineLabel}>ID:</span>
        <span>{text.id}</span>
      </div>
      <div className={s.uiToolsInfoLine}>
        <span className={s.uiToolsInfoLineLabel}>FontSize:</span>
        <NumberInput
          value={text.fontSize}
          setValue={(v) => {
            uiEditorModel.setTextFontSize(text.id, v)
          }}
        />
      </div>
      <div className={s.uiToolsInfoLine}>
        <span className={s.uiToolsInfoLineLabel}>Label:</span>
        <StringInput
          value={text.label}
          setValue={(v) => {
            uiEditorModel.setTextLabel(text.id, v)
          }}
        />
      </div>
      <div className={s.uiToolsInfoLine}>
        <span className={s.uiToolsInfoLineLabel}>Color:</span>
        <input
          className={s.uiToolsInfoLineInput}
          type="color"
          value={fixColorString(text.color)}
          onChange={(ev) => {
            uiEditorModel.setTextColor(text.id, ev.target.value)
          }}
        ></input>
        <StringInput value={text.color} setValue={(v) => uiEditorModel.setTextColor(text.id, v)} />
      </div>
      <Divider />
      <div className={s.uiToolsButtonGroup}>
        <ToolButton
          onEmit={() => uiEditorModel.toggleBold(text.id)}
          label="Blob(B)"
          shortCut="ctrl.B"
          switch={text.bold ? 1 : 0}
        />
      </div>
    </>
  )
}
